#include "sylar/hook.h"

#include "sylar/sylar.h"

#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>

static sylar::Logger::LoggerPtr g_logger = SYLAR_LOG_ROOT();

void test_sleep()
{
    sylar::IOManger iom(1);
    iom.schedule([](){
        sleep(2);
        SYLAR_LOG_INFO(g_logger) << "sleep 2";
    });

    iom.schedule([](){
        sleep(3);
        SYLAR_LOG_INFO(g_logger) << "sleep 3";
    });

    SYLAR_LOG_INFO(g_logger) << "test_sleep";
}

int test_sock()
{
    int sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    inet_pton(AF_INET, "183.2.172.17", &addr.sin_addr.s_addr);

    SYLAR_LOG_ERROR(g_logger) << "begin";
    int rt = connect(sock, (const sockaddr*)&addr, sizeof(addr));
    SYLAR_LOG_ERROR(g_logger) << "connect rt = " << rt << " error=" << errno;
    
    const char data[]  = "GET / HTTP/1.0\r\n\r\n";

    rt = send(sock, data, sizeof(data), 0);

    SYLAR_LOG_ERROR(g_logger) << "send rt = " << rt << " error = " << errno;


    std::string buff;
    buff.resize(4096);
    rt = recv(sock, &buff[0], buff.size(), 0);
    SYLAR_LOG_ERROR(g_logger) << "recv rt = " << rt << " error = " << errno;

    buff.resize(rt);



    SYLAR_LOG_ERROR(g_logger) << buff;

    return 0;
}

int main(int argc, char* argv[])
{
    //test_sleep();
    //test_sock();

    sylar::IOManger iom;
    iom.schedule(test_sock);
    return 0;
}